<?php

/**
 * 合同回款信息仓库
 * @author wangwx 2015-5-12
 */

namespace common\repositories\myhtsq;

use common\entities\ConfigEntity;
use Exception;
use common\repositories\BaseRepository;
use common\support\StringHelper;
use common\error\ErrorCode;
use common\entities\myhtsq\ContractPaymentEntity;

class ContractPaymentRepository extends BaseRepository
{

    /**
     * 构造方法
     * @param unknown $config (optional)
     */
    public function __construct($config = [])
    {
        parent::__construct($config);
    }

    /**
     * 检查是否存在合同id回款
     * @param string $contractId 合同id
     * @return boolean
     */
    public static function isExistContractPayment($contractId)
    {
        return ContractPaymentEntity::find()->where(['contract_id' => $contractId])->exists();
    }

    /**
     * 根据合同ID获取对应的回款信息
     * @param string $contractId 合同ID
     * @return array
     */
    public static function getPaymentInfoByContractId($contractId)
    {
        $query = ContractPaymentEntity::find()
            ->where(['contract_id' => $contractId])
            ->asArray()
            ->all();
        return $query;
    }

    /**
     * 根据回款id获取对应的回款实例
     * @param string $paymentId 回款id
     * @return ContractPaymentEntity
     */
    public static function getPaymentEntityByPaymentId($paymentId)
    {
        $query = ContractPaymentEntity::findOne(['payment_id' => $paymentId]);
        return $query;
    }

    /**
     * 保存合同回款
     * @param common\models\myhtsq\ContractPaymentModel $contractPaymentModel
     * @return boolean|string   失败|回款Guid
     */
    public static function addContractPayment($contractPaymentModel)
    {
        try {
            $entity = new ContractPaymentEntity();
            $entity->setAttributes($contractPaymentModel->attributes);
            $entity->created_on = ConfigEntity::getDbNowDate();

            // 额外处理 todo
            if (isset($contractPaymentModel->withdraw_fee) && $contractPaymentModel->withdraw_fee) {
                $entity->withdraw_fee = $contractPaymentModel->withdraw_fee;
                $entity->withdraw_fee_rate = $contractPaymentModel->withdraw_fee_rate;
            }

            if (!(isset($entity->payment_id) && !empty($entity->payment_id))) {
                $entity->payment_id = StringHelper::uuid();
            }

            $result = $entity->save();
            if ($result === FALSE) {
                return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_FORM_SAVE_FAIL, $entity->firstErrorMessage);
            } else {
                return $entity->primaryKey;
            }
        } catch (Exception $ex) {
            return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_FORM_SAVE_FAIL, $ex->getMessage());
        }
    }

    /**
     * 保存合同回款
     * @param common\models\myhtsq\ContractPaymentModel $contractPaymentModel
     * @return boolean|string   失败|回款Guid
     */
    public static function updateContractPayment($contractPaymentModel)
    {
        try {
            $entity = ContractPaymentEntity::find()->where(['payment_id' => $contractPaymentModel->payment_id])->one();
            if (!isset($entity)) {
                return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_NOT_EXISTS);
            }

            $entity->setAttributes($contractPaymentModel->attributes);
            $entity->modified_on = ConfigEntity::getDbNowDate();
            $result = $entity->update();
            if ($result === false) {
                return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_FORM_SAVE_FAIL, $entity->firstErrorMessage);
            } else {
                return $entity->payment_id;
            }
        } catch (Exception $ex) {
            return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_FORM_SAVE_FAIL, $ex->getMessage());
        }
    }

    /**
     * 根据合同id获取还没有完全关联发票的回款
     * @param string $contractId 合同id
     * @return array
     */
    public static function getContractPaymentHaveAmountByContract($contractId)
    {
        $sql = 'select *
                from 
                (
                        select myscrm_contract_payment.*,
                                ifnull((select sum(cur_payment_amount) from myscrm_invoice_payment where payment_id = myscrm_contract_payment.payment_id),0) as have_payment_amount
                        from myscrm_contract_payment
                ) pay where pay.payment_amount>pay.have_payment_amount and pay.contract_id = :contract_id';
        $query = ContractPaymentEntity::findBySql($sql, [':contract_id' => $contractId])
            ->asArray()
            ->all();
        return $query;
    }

    /**
     *  根据财务编号获取对应的合同回款信息
     * @param string $financeCode
     * @return array
     */
    public static function getContractPaymentInfoByFinanceCode($financeCode)
    {
        $query = ContractPaymentEntity::find()
            ->where(['finance_code' => $financeCode])
            ->asArray()
            ->all();
        return $query;
    }

    public static function getContractPaymentAmountByContractId($contractid){
        $payments = ContractPaymentEntity::find()->where(['contract_id'=>$contractid])->all();
        $sumpaymentamount = 0;
        foreach($payments as $item){
            $sumpaymentamount += floatval($item['payment_amount']);
        }
        return $sumpaymentamount;
    }

    public static function getIsOperationGzx($paymentid){
        $sql = "SELECT IF(cr.is_operation=1,'是','否') isgzx FROM myscrm_invoice_payment p
                inner join myscrm_invoice_receivable ir on p.invoice_receivable_id=ir.invoice_receivable_id
                inner join myscrm_contract_receivable cr on ir.receivable_id=cr.receivable_id
                WHERE p.payment_id=:payment_id";
        $data = ContractPaymentEntity::getDb()->createCommand($sql,[':payment_id'=>$paymentid])->queryAll();
        return $data;
    }
}
